package ar.com.binarit.services

import org.springframework.social.facebook.api.Facebook
import org.springframework.social.facebook.api.FacebookProfile
import org.springframework.social.facebook.api.impl.FacebookTemplate
import org.springframework.transaction.annotation.Transactional;

import ar.com.binarit.Person

class FacebookAuthService {

	static transactional = false

	
	@Transactional(readOnly = true)
	def getFB(accessToken){
		Facebook facebook = new FacebookTemplate(accessToken)
		FacebookProfile fbProfile = facebook.userOperations().userProfile
		return fbProfile
	}
	
	@Transactional
	def cambiarEmail(uid, access){
//		println "uid: ${uid}"
//		println "accessO ${access}"
		def persona = Person.findByUsername("facebook_${uid}")
//		println "persona: ${persona}"
//		println persona?.email
		if (access && persona && !persona.email){
//			def email = this.getFB(access)?.email
//			println "yo reescribo ehhh: ${email}"
//			println "persona: ${persona}"
//			println "usuario.email : ${persona.email }"
			def fbUser = this.getFB(access)
			persona.email = fbUser?.email
			persona.imgAvatar = "https://graph.facebook.com/${fbUser.id}/picture?type=large"
			persona.nickname = fbUser?.name
//			println persona.class
			persona.save(flush: true, failOnError: true)
		}
	}
	
//	@Transactional
//	def cambiarEmail(token){
//		def persona = Person.findByUsername("facebook_${token.uid}")
//		println "persona: ${persona}"
//		println token
//		println persona?.email
//		if (token && token.accessToken && persona && !persona.email){
//			def email = this.getFB(token.accessToken)?.email
//			println "yo reescribo ehhh: ${email}"
//			println "persona: ${persona}"
//			println "usuario.email : ${persona.email }"
//			persona.email = email
//			println persona.class
//			persona.save(flush: true, failOnError: true)
//		}
//
//	}
}
